package com.yaowk.web.common.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.yaowk.web.common.adapter.WebResponseAdapter;
import com.yaowk.web.common.interceptor.LogInterceptor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrationsAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.Date;
import java.util.List;

@Configuration
@Data
public class CommonWebMvcConfig extends WebMvcConfigurerAdapter {
    //@Value("${yaowk.web.cors.enable:true}")
    private boolean crosEnable = true;  // 是否允许cros跨域，默认否
    @Value("${yaowk.web.cors.mapping:/**}")
    private String crosMapping; // 配置cors路径，表示这些路径允许跨域
    @Value("${yaowk.web.cors.allowedOrigins:*}")
    private String allowedOrigins; // 允许的origin
    @Value("${yaowk.web.cors.allowCredentials:true}")
    private boolean allowCredentials; // 是否允许credentials
    @Value("${yaowk.web.cors.allowedMethods:GET,POST,DELETE,PUT}")
    private String allowedMethods; // 跨域允许的方法
    @Value("${yaowk.web.cors.maxAge:3600}")
    private Integer crosMaxAge; // 这个不知道
    @Value("${yaowk.web.fastJson.enable:true}")
    private boolean fastJsonEnable; // 是否使用fastjson序列化
    @Value("${yaowk.web.adapter.responseBody.enable:true}")
    private boolean adapterEnable;


    /**
     * springmvc 自动解析参数  时间戳转时间
     *
     * @return
     */
    @Bean
    public Converter<String, Date> timeStamp2DateConverter() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                return new Date(Long.valueOf(source));
            }
        };
    }

    /**
     * springmvc 返回参数格式化
     *
     * @return
     */
    @Bean
    public WebMvcRegistrationsAdapter webMvcRegistrationsHandlerMapping() {
        return new WebResponseAdapter();
    }

    /**
     * 使用cros解决问题跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        System.out.println(crosEnable);
        System.out.println(allowedMethods);
//        if (crosEnable) {
//            String[] methods = allowedMethods.split(",");
//            registry.addMapping(crosMapping)
//                    .allowedOrigins(allowedOrigins)
//                    .allowCredentials(allowCredentials)
//                    .allowedMethods(methods)
//                    .maxAge(crosMaxAge);
//        }
        registry.addMapping("/**");
    }

    /**
     * 添加日志拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");
    }

    /**
     * 返回值序列化工具配置，使用fastjson替换spring原有的json工具
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        if (fastJsonEnable) {
            //调用父类的配置
            super.configureMessageConverters(converters);
            //创建fastJson消息转换器
            FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
            //创建配置类
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            //修改配置返回内容的过滤
            fastJsonConfig.setSerializerFeatures(
                    SerializerFeature.DisableCircularReferenceDetect,
                    SerializerFeature.WriteMapNullValue,
                    SerializerFeature.WriteNullStringAsEmpty,
                    SerializerFeature.WriteNullListAsEmpty
            );
            fastConverter.setFastJsonConfig(fastJsonConfig);
            //将fastjson添加到视图消息转换器列表内
            converters.add(fastConverter);
        }
    }
}
